<?
	if (isset($_POST['ID']))
	{  
        foreach($_POST['meta'] as $k=>$v)
        {
             $bibtex->saveMeta($user->getID(), $_POST['ID'], $k, $v);
        }        
        refreshPage('index.php', array('p'=>'view', 'ID'=>$_POST['ID']));
    }
    
    if (isset($_GET['suppressWarnings']))
    {
        $bibtex->suppressWarnings($_GET['ID'], $_GET['suppressWarnings'] == 1);
        refreshPage('index.php', array('p'=>'view', 'ID'=>$_GET['ID']));
    }

    $ID = $_GET['ID'];
    $entry = $bibtex->getEntry($ID, false);
    
    if ($entry !== false)
    {
        // Resort
        $fields = $bibtex->getFields($entry['entrytype']);

        $tmp = array();
        
        $entrytype = $entry['entrytype'];
        $tmp['Entry Key'] = $entry['entrykey'];
        
        foreach($fields['req'] as $v)
        {
            $name = $v;
            if ($v == 'author') 
            {
                $name = 'authors';
            }
            $tmp[$name] = $entry[$v];
        }
        foreach($fields['opt'] as $v)
        {
            $name = $v;
            $tmp[$name] = $entry[$v];
        }
        $tmp['abstract'] = $entry['abstract'];
        $entry_clean = $tmp;    


        // Generate Warnings
        $warnings = array();
        $authors = explode(' and ', $entry_clean['authors']);
        foreach($authors as $a)
        {
            $names = explode(',', $a);
            $names[1] = trim($names[1]);
            if ((strpos($names[1], '.') !== false && strpos($names[1], ' ') === false)|| 
                (strpos($names[1], ' ') === false && strlen($names[1]) <= 2))
            {
                $warnings[] = 'Check Name: '.$a;
            }
        } 
        if ($entry_clean['pages'] != '' && strpos($entry_clean['pages'], '--') === false)
        {
            $warnings[] = 'Check Pages';
        }


        // Make Authors into a Smart Search
        if (isset($entry_clean['authors'])) {
            $authors = explode(' and ', $entry_clean['authors']);
            foreach($authors as $k=>$v) {
                $authors[$k] = '<a href="index.php?p=search&amp;q='.urlencode($v).'">'.trim($v).'</a>';
            }
            $entry_clean['authors'] = implode(' and ', $authors);
        }

        // Make Journal into Smart Search
        if (isset($entry_clean['journal'])) {
            $entry_clean['journal'] = '<a href="index.php?p=search&amp;q='.urlencode($entry_clean['journal']).'">'.$entry_clean['journal'].'</a>';
        }
        
        $smarty->assign('entry', $entry_clean);
        $smarty->assign('entrytype', $entrytype);
        $smarty->assign('entryID', $ID);
        $smarty->assign('warnings', $warnings);
        $smarty->assign('suppressWarnings', ($entry["suppressWarnings"] == 1));
        
        // Gather history
        $history = array();
        $history[] = array('time'=>$entry['added'], 'desc'=>'<strong>'.$user->getFullname($entry['user']).'</strong> added this '.$entrytype.'.');
        $record = $bibtex->getHistory($ID);
        foreach($record as $r)
        {
            if ($r['old'] == '')
            {
                $r['old'] = '<span style="color: #00f; margin: 0;">Empty Field</span>';
            }
            if ($r['new'] == '')
            {
                $r['new'] = '<span style="color: #00f; margin: 0;">Empty Field</span>';
            }
            $history[] = array('time'=>$r['timestamp'], 'desc'=>'<strong>'.$user->getFullname($r['user']).'</strong> changed <strong>'.$r['field'].'</strong> from <em>'.$r['old'].'</em> <strong>-></strong> <em>'.$r['new'].'</em>.');
        }
        $history = array_reverse($history);
        $smarty->assign('history', $history);

        /*******************
         FILE DOWNLOAD STUFF
         *******************/
        $filename = $bibtex->getFilename($ID);
        if ($filename !== false)
        {
            $smarty->assign('filename', $filename);
        }

        /******************
         CREATE PNG PREVIEW
         ******************/
        $preview = $bibtex->getPreview($ID);
        if ($preview !== false)
        {
            $smarty->assign('preview', $preview);
        }
        
        /******************
         PROJECT MANAGEMENT 
         ******************/
        $sql = 'SELECT * FROM project_entries WHERE entryID=:entryID';
        $query = $db->prepare($sql);
        $query->execute(array(':entryID'=>$ID));
        $project_entries = $query->fetchAll();
        $sql = 'SELECT * FROM projects WHERE userID=:userID';
        $query = $db->prepare($sql);
        $query->execute(array(':userID'=>$user->getID()));
        $projects = $query->fetchAll();
        $sql = 'SELECT * FROM project_folders WHERE projectID=:projectID';
        $query = $db->prepare($sql);
        foreach($projects as $k=>$v) {
            $projects[$k]['inproject'] = false;
            foreach ($project_entries as $k2=>$v2) {
                if ($v["ID"] == $v2["projectID"] && $v2["folderID"] == 0) $projects[$k]['inproject'] = true;
            }
            $query->execute(array(':projectID'=>$v['ID']));
            $projects[$k]["folders"] = $query->fetchAll();
            foreach ($projects[$k]["folders"] as $k2=>$v2) {
                $projects[$k]["folders"][$k2]['inproject'] = false;
                foreach ($project_entries as $k3=>$v3) {
                    if ($v2["ID"] == $v3["folderID"]) $projects[$k]["folders"][$k2]['inproject'] = true;
                }
            }
        }
        $smarty->assign('projects', $projects);
        
        /*****************
         META DATA MADNESS
         *****************/
         $fields = $bibtex->getMetaFields($user->getID());
         $values = $bibtex->getMetaValues($user->getID(), $ID);       
         $meta = array();
         foreach($fields as $f)
         {
            if (isset($values[$f["ID"]]))
            {
                switch($f['type'])
                {
                    case 'st':
                    case 'lt':
                    case 'il':
					case 'dt':
                        $meta[$f["name"]] = $values[$f["ID"]];
                    break;
                    
                    case 'kw':
                        $val = '<ul>';
                        foreach ($values[$f["ID"]] as $v)
                        {
                            $val .= '<li>'.$v.'</li>';
                        }
                        $val .= '</ul>';
                        $meta[$f["name"]] = $val;
                    break;
                }
            }
         }
         $smarty->assign("metadata", $meta);        
         
        /*****************************************************
         Metadata Excitement Happens Hear and You're Invited
         *****************************************************/
        $smarty->assign('metafields', $bibtex->getMetaFields($user->getID()));
        $smarty->assign('metavalues', $bibtex->getMetaValues($user->getID(), $ID));
           
        if (isset($_POST['meta']))
        {
            // A POST takes precedence over previously saved values if any.
            $values = array();
            foreach($_POST['meta'] as $k=>$v)
            {
                $values[$k] = $v;
            }
            $smarty->assign('metavalues', $values);
        }
         
        
    }
    else
    {
        $error[] = 'Reference not found.';
    }
?>
